package com.boot.unity.api.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableSwagger2
@EnableKnife4j
@ConditionalOnProperty(name = "swagger2.enable",matchIfMissing = true)
public class SwaggerConfig {
    private static final List<String> DEFAULT_EXCLUDE_PATH = Arrays.asList("/", "/error", "/generate", "/actuator/**", "/swagger", "/doc");
    private static final String BASE_PATH = "/**";

    @Bean
    public Docket docket() {

        List<Predicate<String>> basePath = new ArrayList();
        basePath.add(PathSelectors.ant(BASE_PATH));

        List<Predicate<String>> excludePath = new ArrayList<>();
        DEFAULT_EXCLUDE_PATH.forEach(path -> excludePath.add(PathSelectors.ant(path)));

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("Unity-API接口文档")
                .apiInfo(apiInfo())
                .select()
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
                .build();
    }

    private ApiInfo apiInfo(){
        String description = "URL格式为：/servicename?v={version}&ts={timestamp}&sign={sign_str}&user={cert_sn}\n" +
                "其中:\n" +
                "servicename:接口服务名；\n" +
                "version:协议版本，目前使用“1.0.0.e2”。其中e？代表所使用的加密算法，e1-SHA1，e2-SHA256，e3-SHA512。\n" +
                "timestamp:发送方的当前时间戳，从格林威治时间1970年01月01日00时00分00秒起至现在的毫秒数。请确保系统时间的准确性，不允许同一发送方在多个数据包中使用同一个时间戳，否则将返回相应错误码；\n" +
                "sign_str:通过加密算法将data、timestamp以及密钥做为参数生成的一串加密字符串；\n" +
                "cert_sn:用户证书的证书序列号，以16进制大写形式表现。\n";
        return new ApiInfoBuilder()
                .title("Unity-API接口文档")
                .description(description)
                .contact(new Contact("unity Co.,Ltd.", "", "unity@unity.com"))
                .version("1.0.0")
                .build();
    }
}
